package handler

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"

	"github.com/gorilla/mux"

	"forum/pkg/domain"
	"forum/pkg/model/helper"
	"forum/pkg/model/session"
)

type profileHandler struct {
	profileSvc domain.ProfileService
}

func NewProfileHandler(profileSvc domain.ProfileService) domain.ProfileHandler {
	return &profileHandler{
		profileSvc: profileSvc,
	}
}

func (h *profileHandler) GetProfileSettings(w http.ResponseWriter, r *http.Request) {
	sess, err := session.GetSession(r)
	if err != nil {
		helper.ResponseErrJSON(w, http.StatusUnauthorized, errors.New("please login first"))
		return
	}

	userID := sess.Values["user_id"].(string)

	profile, err := h.profileSvc.GetProfileByUserID(userID)
	if err != nil {
		helper.ResponseText(w, http.StatusInternalServerError, "")
		log.Println(err)
		return
	}

	d := map[string]interface{}{
		"profile": profile,
	}
	helper.ResponseJSON(w, http.StatusOK, d)
}

func (h *profileHandler) UpdateProfileSettings(w http.ResponseWriter, r *http.Request) {
	sess, err := session.GetSession(r)
	if err != nil {
		helper.ResponseErrJSON(w, http.StatusUnauthorized, errors.New("please login first"))
		return
	}

	profile := &domain.Profile{}
	if err := json.NewDecoder(r.Body).Decode(profile); err != nil {
		helper.ResponseText(w, http.StatusBadRequest, "")
		return
	}
	profile.UserID = sess.Values["user_id"].(string)

	if err := h.profileSvc.UpdateProfile(profile); err != nil {
		helper.ResponseText(w, http.StatusInternalServerError, "")
		log.Println("update profile error:", err)
		return
	}

	d := map[string]interface{}{
		"profile": profile,
	}

	helper.ResponseJSON(w, http.StatusOK, d)
}

func (h *profileHandler) GetProfileSettingsByName(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	username := vars["username"]
	profile, err := h.profileSvc.GetProfileByName(username)
	if err != nil {
		helper.ResponseErrJSON(w, http.StatusBadRequest, fmt.Errorf("user not found"))
		log.Println("get profile by name error:", err)
		return
	}

	d := map[string]interface{}{
		"profile": profile,
	}
	helper.ResponseJSON(w, http.StatusOK, d)
}
